﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Web;
using HtmlAgilityPack;
using ClassLibrary1;

namespace ChordComponent
{
    public class KomponenChord
    {
        private HtmlWeb htmlweb = new HtmlWeb();
        private HtmlDocument htmldoc = new HtmlDocument();
        private object responseStream;

        public static string patternChord = @"^[A-G](b|#)?((m(aj)?|M|aug|dim|sus)([2-7]|9|13)?)?(\/[A-G](b|#)?)?$";

        //public List<string> listChord = new List<string>();

        //Tuple<string, bool> chordLyric = new Tuple<string, bool>("woe", true);

        public static List<Tuple<string, bool>> listStringHasil = new List<Tuple<string, bool>>();
        private static bool okAdd = false;

        private List<string> removeDuplicate(List<string> check)
        {
            List<string> result = new List<string>();
            foreach (string cek in check)
            {
                if (result.Contains(cek) == false)
                {
                    result.Add(cek);
                }
            }
            return result;
        }

        private static void traverse(HtmlNode cur)
        {
            if (cur == null) return;

            if (cur.ParentNode.OriginalName == "span")
            {
                okAdd = true;
            }

            if (cur.OriginalName == "#text")
            {
                if (okAdd)
                {
                    if (cur.ParentNode.OriginalName == "span")
                        listStringHasil.Add(new Tuple<string, bool>(cur.InnerText, true));
                    else
                        listStringHasil.Add(new Tuple<string, bool>(cur.InnerText, false));
                }
            }

            traverse(cur.FirstChild);
            traverse(cur.NextSibling);
        }

        private static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                using (var stream = client.OpenRead("http://www.ultimate-guitar.com/"))
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public List<string> getURLbyArtist(string keywords)
        {
            List<string> hasil = new List<string>();
            for (int i = 1; i < 6; i++)
            {
                HtmlDocument document = new HtmlDocument();
                HtmlWeb web = new HtmlWeb();
                string stringLengkap = null;
                string searchKey = null;
                string checkedKey = null;
                searchKey = keywords.Replace(" ", "+");
                checkedKey = keywords.Replace(" ", "_");

                try
                {
                    string url = "http://www.ultimate-guitar.com/search.php?title=" + keywords + "&page=" + i + "&tab_type_group=text&app_name=ugt&order=myweight";
                    htmldoc = htmlweb.Load(url);
                    HtmlNodeCollection nodes = htmldoc.DocumentNode.SelectNodes("//a[@class='song']");
                    if (nodes == null)
                        break;

                    foreach (HtmlNode node in nodes)
                    {
                        if (node.Attributes["href"].Value.Contains("crd"))
                        {
                            string[] cekArtis = node.Attributes["href"].Value.Split('/');
                            if (cekArtis[4].Contains(checkedKey))
                            {
                                cekArtis[5] = cekArtis[5].Substring(0, (cekArtis[5].Length) - 8);
                                stringLengkap = cekArtis[4];
                                stringLengkap = string.Concat(stringLengkap, "~", cekArtis[5]);
                                stringLengkap = string.Concat(stringLengkap, "~", node.Attributes["href"].Value);
                                hasil.Add(stringLengkap);
                            }
                        }
                    }
                }
                catch (WebException e)
                {
                    hasil.Add(e.Message);
                }
            }
            return removeDuplicate(hasil);
        }

        public List<string> getURLbyTitle(string keywords)
        {
            List<string> hasil = new List<string>();
            HtmlDocument document = new HtmlDocument();
            string stringLengkap = null;
            string searchKey = null;
            string checkedKey = null;
            searchKey = keywords.Replace(" ", "+");
            checkedKey = keywords.Replace(" ", "_");

            for (int i = 1; i < 6; i++)
            {
                string url = "http://www.ultimate-guitar.com/search.php?title=" + keywords + "&page=" + i + "&tab_type_group=text&app_name=ugt&order=myweight";
                htmldoc = htmlweb.Load(url);
                HtmlNodeCollection nodestitle = document.DocumentNode.SelectNodes("//a[@class='song']");
                string coba = nodestitle.ToString();
                hasil.Add(coba);

                if (nodestitle != null)
                {
                    foreach (HtmlNode node in document.DocumentNode.SelectNodes("//a[@class='song']"))
                    {
                        if (node.Attributes["href"].Value.Contains("crd"))
                        {
                            string[] cekJudul = node.Attributes["href"].Value.Split('/');
                            if (cekJudul[5].Contains(checkedKey))
                            {
                                cekJudul[5] = cekJudul[5].Substring(0, (cekJudul[5].Length) - 8);
                                stringLengkap = cekJudul[4];
                                stringLengkap = string.Concat(stringLengkap, "~", cekJudul[5]);
                                stringLengkap = string.Concat(stringLengkap, "~", node.Attributes["href"].Value);
                                hasil.Add(stringLengkap);
                            }
                        }
                    }
                }
            }
            return hasil;
        }

        //http://www.guitarfriendly.net/images/chords/diagrams/a-major-chord.jpg

        public void getLyricAndChord(string keywords)
        {
            string result = null;
            //string[] resultArray;
            HtmlWeb web = new HtmlWeb();
            HtmlDocument document = new HtmlDocument();

            document = web.Load(keywords);
            int cc = 0;
            HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//pre");
            okAdd = false;
            listStringHasil = new List<Tuple<string, bool>>();

            foreach (HtmlNode node in nodes)
            {
                ++cc;
                result = node.InnerText;
                if (cc == 2)
                {
                    traverse(node);
                }
            }
            //return result;
        }

        public string getChordOnly(string cmpChord)
        {
            string hasil = null;

            try
            {
                hasil = @"http://justinguitar.com/images/CH_images/Chord-O-" + cmpChord + ".gif";

                //string getUrl = "http://justinguitar.com/images/CH_images/Chord-O-" + cmpChord + ".gif";
                //System.Net.WebRequest request = System.Net.WebRequest.Create(getUrl);
                //System.Net.WebResponse response = request.GetResponse();
                //System.IO.Stream responseStream = response.GetResponseStream();
                //Bitmap bmp = new Bitmap(getUrl);
                //responseStream.Dispose();
                //return bmp;
            }
            catch (WebException e)
            {
                hasil = e.Message;
            }

            return hasil;
        }
    }
}
